package com.wealth.merchant.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.order.service.IVoucherRecordService;
import com.wealth.platform.entity.SldConfig;
import com.wealth.platform.enums.SldConfigTypeEnum;
import com.wealth.platform.service.ISldConfigService;
import com.wealth.system.entity.User;
import com.wealth.system.service.IUserService;
import com.wealth.system.web.controller.BaseController;
import com.wealth.wechat.entity.WechatConfig;
import com.wealth.wechat.service.WechatConfigService;

import iaas.enums.StatusEnum;
import iaas.utils.MatrixToImageWriter;
import iaas.utils.ResultObject;

/**
 * 商户登录
 * @author chan
 */
@Controller
@RequestMapping(value="/merchant")
public class MerchantController extends BaseController{

	Logger logger = Logger.getLogger(MerchantController.class);
	
	@Autowired
	private IUserService userService;
	@Autowired
	private IVoucherRecordService recordService;
	@Autowired
	private IMerchantService merchantService;
	@Autowired
	private WechatConfigService wechatConfigService;
	@Autowired
	private ISldConfigService sldConfigService;
	
	
	
	/** 
	 * 商户登录页面
	 */
	@RequestMapping(value="/login")
	public String loginForm(Model model) {
		return "merchant/login";
	}
	
	/** 
	 * 商户登录
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public ResultObject login(@RequestParam String username,@RequestParam String password) {
		try{
			User user = userService.findUserByUsername(username);
			if(user==null){
				return new ResultObject("501", "用户不存在", "");
			}
			if(user.getStatus()!=StatusEnum.NORMAL.getValue() ){
				return new ResultObject("502", "商户被禁止登陆,请联系管理员", "");
			}
			if(!user.getPassword().equals(password)){
				return new ResultObject("503", "用户名或密码错误", "");
			}
			Merchant merchant = merchantService.getMerchantByUserId(user.getId());
			return new ResultObject("000", "商户登录成功", merchant.getId());
		}catch(Exception e){
			return new ResultObject("999", "商户登录错误", "");
		}
	}
	
	
	/**
	 * 生成二维码
	 */
	@RequestMapping(value="/generateQrcode")
	public void qrcode(HttpServletRequest request,HttpServletResponse response,String code,Long memberid,int height,int width) throws IOException{
		try {
			response.setHeader("Cache-Control", "no-catch");
			response.setContentType("image/jpeg");
			
			SldConfig config = sldConfigService.getSldConfigByCorpIdAndType(corpid,SldConfigTypeEnum.WECHAT.getValue());
			String url = config.getDomain()+"/merchant/scanQrcodeResult?code="+code+"&memberid="+memberid;
			
			String format = "jpg";// 图像类型  
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
	        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 
			BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height,hints);// 生成矩阵  
			MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream() );
		} catch (Exception e) {
		}
	} 
	
	
	/** 
	 * 商户扫码页面
	 */
	@RequestMapping(value="/scanQrcode")
	public String scanQrcodeForm(Model model,@RequestParam Long merchantid) {
		
		WechatConfig config = wechatConfigService.getWechatConfigByCorpid(corpid);
		model.addAttribute("config", config);
		
		model.addAttribute("merchantid", merchantid);
		
		model.addAttribute("corpid", corpid);
		return "merchant/scanQrcode";
	}
	
	/** 
	 * 验证后，跳转到页面
	 */
	@RequestMapping(value="/scanQrcodeResult")
	public String resultForm(
			Model model,
			@RequestParam String code,
			@RequestParam Long memberid,
			@RequestParam(required=false) Long merchantid) {
		try{
			//非商户验证
			if(merchantid==null){
				ResultObject rs  = new ResultObject("500", "请登录商户号扫码", null);
				model.addAttribute("rs", rs);
			}else{
				ResultObject rs = recordService.validVoucherRecord(memberid, merchantid, code);
				model.addAttribute("rs", rs);
			}
			
			return "merchant/scanQrcodeResult";
		}catch(Exception e){
			return "system/500";
		}
	}
	
	
	
	/**
	 * 商户地址页面
	 */
	@RequestMapping(value = "/map/{merchantid}")
	public String map(Model model,@PathVariable Long merchantid) {
		try {
			Merchant merchant = merchantService.get(merchantid);
			model.addAttribute("merchant", merchant);
			return "merchant/map";
		} catch (Exception e) {
			logger.error(e);
			return "system/500";
		}
	}
}
